<?php
declare (strict_types = 1);

namespace app\listener;

use app\model\Goods;
use app\model\IntegralLog;
use app\model\User;
use think\facade\Db;

class ModifyIntegral
{

    /**
     * 事件监听处理
     * @param $integral
     * @return bool
     * @throws \think\db\concern\PDOException
     */
    public function handle($integral)
    {
        //
        $uid = config('user.id');
        $remark = '';
        $num = mt_rand(1,5);

        if($integral->type == IntegralLog::PLAY_VIDEO){
            //播放视频
            $remark = '观看视频'.$integral->remark;
        }
        elseif($integral->type == IntegralLog::GOODS_EXCHANGE){
            //兑换商品
            $goodsId = $integral->way;
            $goodsModel = new Goods();

            $goodsInfo = $goodsModel->getGoodsInfoById($goodsId);
            $remark = '使用积分兑换了'.$integral->remark;
            $num = 0 - $goodsInfo['exchangeIntegral'];
        }
        elseif($integral->type == IntegralLog::SIGN_IN){
            //兑换商品
            $remark = '打卡';
        }

        $integralLog = [
            'integral_uid' => $uid,
            'integral_way' => $integral->way,
            'integral_type' => $integral->type,
            'integral_num' => $num,
            'integral_remark' => $remark
        ];

        $integralLogModel = new IntegralLog();
        $addRet = $integralLogModel->addLog($integralLog);
        if(!$addRet){
            Db::rollback();
        }

        //修改客户总积分
        $userModel = new User();

        $userModel->modifyUserIntegral($uid,$num);
        return (int)$num;
    }

}
